package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.model.result.StarInfoResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushExtHandleService;
import com.block.datapush.service.apipush.utils.LongYanUtil;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 龙焱 掩码全流程
 */
@Service
public class LongYanMaskApisService implements IPushApiService, IPushApi2Service, IPushExtHandleService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone_code", memberSourceInfo.getMobile().substring(0, 8));
        bizMap.put("working_city", memberSourceInfo.getCity());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("idCardPreFix4", memberSourceInfo.getIdcard().substring(0, 4));
        bizMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        bizMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        bizMap.put("sex", memberSourceInfo.getSex()==1?1:2);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gjj", LongYanUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", LongYanUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("loan_amount", LongYanUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", LongYanUtil.getHouse(memberSourceInfo.getHouse()));
        Integer car = LongYanUtil.getCar(memberSourceInfo.getCar());
        bizMap.put("car", car);
        if(StrUtil.equals(String.valueOf(car),"1")){
            bizMap.put("car_status", 1);
            bizMap.put("car_price", 99);
        }else {
            bizMap.put("car_status", 99);
            bizMap.put("car_price", 99);
        }

        bizMap.put("overdue", LongYanUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("zhima", LongYanUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("occupation", LongYanUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("insurance", LongYanUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【龙焱全流程】撞库开始【queryUrl】{}【bizMap】{}【headerMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【龙焱全流程】撞库结束【result】{}", resultObject);

        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setResultInfo(result);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));

        if (StrUtil.equals(String.valueOf(code),"0")) {
            JSONObject data = resultObject.getJSONObject("data");
            String logo = data.getString("product_logo");
            String orderId = data.getString("order_id");
            String productLoan = data.getString("product_loan");
            String maxLoanRate = data.getString("product_ratio");
            String productName = data.getString("product_name");
            String institutionName = data.getString("company_name");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo", orderId);
            infoObject.put("productId", orderId);
            infoObject.put("productName", productName);
            infoObject.put("companyName", institutionName);
            infoObject.put("companyLogo", logo);
            infoObject.put("maxLoanAmount", productLoan);
            infoObject.put("maxLoanRate", maxLoanRate);
            infoObject.put("minLoanRate", "1");
            infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("product_agreement");
            for (int i = 0; i < protocolList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                String protocolName = protocolList.getJSONObject(i).getString("name");
                String protocolUrl = protocolList.getJSONObject(i).getString("url");
                jsonObject.put("protocalName", protocolName);
                jsonObject.put("protocalUrl", protocolUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList", jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);
            JSONArray md5List = data.getJSONArray("md5_list");
            String mobileMd5 = memberSourceInfo.getMobileMd5();
            if (MobileMd5IsInListUtils.isMobileMd5InList(md5List, mobileMd5)) {
                // 存在
                pushApiResult.setCode(code + "|" + "500");
                pushApiResult.setMessage(message + "|" + mobileMd5 + "号码已存在");
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
                BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                if (price.compareTo(new BigDecimal(0.00)) == -1) {
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save) {
                pushApiResult.setPushSuccess(true);
                extJson.put("traceId", orderId);
            } else {
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;

    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getRegisterUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String traceId = extJson.getString("traceId");

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("idno", memberSourceInfo.getIdcard());
        bizMap.put("order_id", traceId);

        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【龙焱全流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【龙焱全流程】导单结束【result】{}", resultObject);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(message);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 0) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (code == 0) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("message","success");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String apiSecret = pushApiKeyParam.getApiSecret();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone_code", memberSourceInfo.getMobileMask().substring(0, 8));
        bizMap.put("working_city", memberSourceInfo.getCity());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("idCardPreFix4", memberSourceInfo.getIdcard().substring(0, 4));
        bizMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        bizMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        bizMap.put("sex", memberSourceInfo.getSex()==1?1:2);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gjj", LongYanUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("shebao", LongYanUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("loan_amount", LongYanUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("house", LongYanUtil.getHouse(memberSourceInfo.getHouse()));
        Integer car = LongYanUtil.getCar(memberSourceInfo.getCar());
        bizMap.put("car", car);
        if(StrUtil.equals(String.valueOf(car),"1")){
            bizMap.put("car_status", 1);
            bizMap.put("car_price", 99);
        }else {
            bizMap.put("car_status", 99);
            bizMap.put("car_price", 99);
        }

        bizMap.put("overdue", LongYanUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("zhima", LongYanUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("occupation", LongYanUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("insurance", LongYanUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("data", encrypt);

        log.info("【上游龙焱全流程】撞库开始【queryUrl】{}【bizMap】{}【headerMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(headerMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(headerMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【上游龙焱全流程】撞库结束【result】{}", resultObject);

        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        pushApiResult.setCode(code+"");
        pushApiResult.setMessage(message);
        pushApiResult.setResultInfo(result);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));

        if (StrUtil.equals(String.valueOf(code),"0")) {
            JSONObject data = resultObject.getJSONObject("data");
            String logo = data.getString("product_logo");
            String orderId = data.getString("order_id");
            String productLoan = data.getString("product_loan");
            String maxLoanRate = data.getString("product_ratio");
            String productName = data.getString("product_name");
            String institutionName = data.getString("company_name");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo", orderId);
            infoObject.put("productId", orderId);
            infoObject.put("productName", productName);
            infoObject.put("companyName", institutionName);
            infoObject.put("companyLogo", logo);
            infoObject.put("maxLoanAmount", productLoan);
            infoObject.put("maxLoanRate", maxLoanRate);
            infoObject.put("minLoanRate", "1");
            infoObject.put("businessInfo", pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("product_agreement");
            for (int i = 0; i < protocolList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                String protocolName = protocolList.getJSONObject(i).getString("name");
                String protocolUrl = protocolList.getJSONObject(i).getString("url");
                jsonObject.put("protocalName", protocolName);
                jsonObject.put("protocalUrl", protocolUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList", jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);
            JSONArray md5List = data.getJSONArray("md5_list");
            pushApiResult.setMd5List(md5List);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)) {
                BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
                if (price.compareTo(new BigDecimal(0.00)) == -1) {
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = price.divide(typeRate);//分润前价格
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(price);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save) {
                pushApiResult.setPushSuccess(true);
                extJson.put("traceId", orderId);
            } else {
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }
        return pushApiResult;
    }

    @Override
    public StarInfoResult handleStarInfo(MerchantBaseInfo merchantBaseInfo, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        return null;
    }
}
